package util.xml;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

public class XmlUtil {

	public static String xmlToString(Document node) {
        try {
    	    // CONVIERTE EN STRING EL Document
        	System.out.println("XmlUtil::xmlToString("+node.toString()+")");
        	TransformerFactory tf = TransformerFactory.newInstance();
        	Transformer transformer = tf.newTransformer();
//        	transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        	StringWriter writer = new StringWriter();
        	transformer.transform(new DOMSource(node), new StreamResult(writer));
        	String output = writer.getBuffer().toString();//.replaceAll("\n|\r", "");
        	System.out.println("Se genero un xml:"+ output);
//        	Source source = new DOMSource(node);
//            StringWriter stringWriter = new StringWriter();
//            Result result = new StreamResult(stringWriter);
//            TransformerFactory factory = TransformerFactory.newInstance();
//            Transformer transformer = factory.newTransformer();
//            transformer.transform(source, result);
//            System.out.println(stringWriter.getBuffer().toString());
            return output;//stringWriter.getBuffer().toString();
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return "error en parser";
    }
	
	public static Document stringToXml(String xml)
	{
		System.out.println("XmlUtil::xmlToString("+xml+")");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try{
			//Crea instancia de DocumentBuilderFactory
			DocumentBuilder builder = factory.newDocumentBuilder();
			//obtiene objeto DocumentBuilder
			// Use String reader  
            Document doc = builder.parse( new InputSource(  
                    new StringReader( xml ) ) );  
			//accede directamente al nodo raiz del documento
			return  doc;
		} 
		catch (Exception e) {
				e.printStackTrace();
		}
		return null;
	}
}
